package com.android.inestpin.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

import com.android.inestpin.R;
import com.android.inestpin.activity.mine.LoginActivity;
import com.android.inestpin.activity.mine.TransparentActivity;
import com.android.inestpin.app.BaseActivity;
import com.android.inestpin.model.MainTabData;
import com.android.inestpin.model.cartPayCallback;
import com.android.inestpin.model.cartPayData;
import com.android.inestpin.model.checkoutcartCallback;
import com.android.inestpin.model.checkoutcartdata;
import com.android.inestpin.model.detail.paydetail;
import com.android.inestpin.model.detail.paydetailCallback;
import com.android.inestpin.model.detail.paydone;
import com.android.inestpin.model.detail.paydoneCallback;
import com.android.inestpin.model.detail.paydonetoshare;
import com.android.inestpin.model.detail.paydonetoshareCallback;
import com.android.inestpin.model.detail.wchatpaydone;
import com.android.inestpin.model.detail.wchatpaydone2;
import com.android.inestpin.model.detail.wchatpaydoneCallback;
import com.android.inestpin.model.detail.wchatpaydoneCallback2;
import com.android.inestpin.model.feeShoppingCallback;
import com.android.inestpin.model.feeShoppingdata;
import com.android.inestpin.model.member.CalculateShippingCostsData;
import com.android.inestpin.model.member.ajaxCalculateShippingCostsCallback;
import com.android.inestpin.utils.ConstantsUrl;
import com.android.inestpin.utils.HttpUtils;
import com.android.inestpin.utils.LoginState;
import com.android.inestpin.utils.MyLog;
import com.android.inestpin.utils.ObjectUtils;
import com.android.inestpin.utils.alipay.PayResult;
import com.android.inestpin.view.MyListView;
import com.android.inestpin.view.detail.PopPaycoupn;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


public class jgtPayActivity extends BaseActivity implements TextWatcher, BaseQuickAdapter.RequestLoadMoreListener  {
    @BindView(R.id.pay_goods_store_name)
    TextView payGoodsStoreName;
    @BindView(R.id.fright_style_list)
    NestFullListView fright_style_list;

//    @BindView(R.id.pay_goods_thumb)
//    ImageView payGoodsThumb;
//    @BindView(R.id.pay_goods_title)
//    TextView payGoodsTitle;
//    @BindView(R.id.pay_goods_price_team)
//    TextView payGoodsPriceTeam;
//    @BindView(R.id.pay_goods_price)
//    TextView payGoodsPrice;
//    @BindView(R.id.pay_goods_price_spec)
//    TextView payGoodsPriceSpec;
//    @BindView(R.id.btn_minus)
//    Button btnMinus;
//    @BindView(R.id.edit_num)
//    EditText editNum;
//    @BindView(R.id.btn_plus)
//    Button btnPlus;
    @BindView(R.id.pay_coupon_store_tv)
    TextView payCouponStoreTv;
    @BindView(R.id.pay_coupon_store_ll)
    LinearLayout payCouponStoreLl;
    @BindView(R.id.pay_msg_edit)
    EditText payMsgEdit;
    @BindView(R.id.pay_price_total)
    TextView payPriceTotal;
    @BindView(R.id.pay_price_deposit)
    TextView payPriceDeposit;
    @BindView(R.id.pay_price_deposit_ll)
    LinearLayout payPriceDepositLl;
    @BindView(R.id.pay_radio_express)
    RadioButton payRadioExpress;
    @BindView(R.id.pay_radio_self)
    RadioButton payRadioSelf;
    @BindView(R.id.pay_address_add_ll)
    LinearLayout payAddressAddLl;
    @BindView(R.id.pay_address_nameaphone)
    TextView payAddressNameaphone;
    @BindView(R.id.pay_address_address)
    TextView payAddressAddress;
    @BindView(R.id.pay_address_ll)
    LinearLayout payAddressLl;
    @BindView(R.id.pay_address_self_ll)
    NestFullListView payAddressSelfLl;
    @BindView(R.id.pay_coupon_general_tv)
    TextView payCouponGeneralTv;
    @BindView(R.id.pay_coupon_general_ll)
    LinearLayout payCouponGeneralLl;
    @BindView(R.id.pay_coupon_teamer_tv)
    TextView payCouponTeamerTv;
    @BindView(R.id.pay_coupon_teamer_ll)
    LinearLayout payCouponTeamerLl;
    @BindView(R.id.pay_style_list)
    NestFullListView payStyleList;
    @BindView(R.id.pay_tip)
    TextView payTip;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.pay_balance_use)
    CheckBox payBalanceUse;
    @BindView(R.id.tv_balance_name)
    TextView tv_balance_name;
    @BindView(R.id.activity_balance_ll)
    LinearLayout activity_balance_ll;
    @BindView(R.id.rb_balance_check)
    RadioButton rb_balance_check;


    @BindView(R.id.pay_price_pay)
    TextView payPricePay;
    @BindView(R.id.pay_post)
    TextView payPost;
    @BindView(R.id.pay_address_self_empty_tv)
    TextView pay_address_self_empty_tv;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    @BindView(R.id.pay_radio_ll)
    RadioGroup payRadioLl;
    @BindView(R.id.pay_address)
    FrameLayout payAddress;
    @BindView(R.id.pay_address_take_ll)
    FrameLayout pay_address_take_ll;
    @BindView(R.id.listView)
    MyListView mRecyclerView;
    @BindView(R.id.pay_express_general_ll)
    LinearLayout pay_express_general_ll;
    @BindView(R.id.pay_express_price_tv)
    TextView pay_express_price_tv;
    @BindView(R.id.pay_express_name_tv)
    TextView pay_express_name_tv;

    private LinearLayoutManager mLayoutManager;
    private boolean networkConnected;
    private Double price_team;
    private int typeid;
    private String common_id = "";
    private ArrayList<MainTabData> mSortListdata = new ArrayList<>();
    private jgtPayActivity mcontext;
    private paydetail.DataBean data;
    private boolean isReallyOrder_flag;
    private ArrayList<String> cartidlist;
    private String spec = "";
    private String addressid = null;
    private int buy_num_limit = 1;
    private String token;
    private int buy_num;
    private int pospay = 0;
    private int posexpress = -1;
    private String[] pay_ids = new String[2];
    private String pay_id = "42";
    private String pay_style;
    private String take_address_id = "0";
    private String express_id = "";
    private double deposit;
    private String option = "";
    private MainTabData weixindata = new MainTabData();
    private MainTabData apliydata = new MainTabData();
    private SharedPreferences sharedPreferences;
    private AdaptList2 adapter2;
    private String totalPrice ;
    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2017051007189701";
    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "2088911179397641";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static final String TARGET_ID = "111111";
    /**
     * 微信注册类
     */
    private IWXAPI iwxapi;
    private String orderInfo;
    private String order_sn;
    private boolean isUseBalance = true;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(mcontext, "支付成功", Toast.LENGTH_SHORT).show();
                        GetToSharePage();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        if (TextUtils.equals(resultStatus, "8000") || TextUtils.equals(resultStatus, "6004")) {
                            ObjectUtils.toast(mcontext, "支付结果确认中");
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            ObjectUtils.toast(mcontext, "支付取消");
                        } else if (TextUtils.equals(resultStatus, "6002")) {
                            ObjectUtils.toast(mcontext, "网络异常");
                        } else if (TextUtils.equals(resultStatus, "5000")) {
                            ObjectUtils.toast(mcontext, "重复请求");
                        } else {
                            // 其他值就可以判断为支付失败
                            ObjectUtils.toast(mcontext, "支付失败");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };
    private String logID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_jgt);
        ButterKnife.bind(this);
        mcontext = jgtPayActivity.this;
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String appName = getResources().getString(R.string.app_name);
        initTitle(0, appName);
        initUI();
        checkout();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private boolean isCheck = true;

    private void initUI() {
        cartidlist = getIntent().getStringArrayListExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_ID);
         totalPrice=getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_TOTAL);

        for (int i=0;i<cartidlist.size();i++){
            MyLog.e("inest","cartidlist="+cartidlist.get(i));
        }
        typeid = getIntent().getIntExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_TYPEID, 0);
//        buy_num = Integer.parseInt(getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_NUM));
//        spec = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_SPEC);
//        common_id = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_COMMON_ID);
//        option = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_OPTION);
//        logID = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_LOG_ID);
        payRadioExpress.setChecked(true);
        payAddress.setVisibility(View.VISIBLE);
        pay_address_take_ll.setVisibility(View.GONE);
        payRadioLl.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                int radioButtonId = radioGroup.getCheckedRadioButtonId();
                if (radioButtonId == R.id.pay_radio_express) {
                    isCheck = true;
//                    express_id = "12";
                    payAddress.setVisibility(View.VISIBLE);

                    pay_address_take_ll.setVisibility(View.GONE);
                    pay_express_general_ll.setVisibility(View.VISIBLE);
                    fright_style_list.setVisibility(View.VISIBLE);
//                    tv_express_title.setVisibility(View.VISIBLE);
                } else {
                    isCheck = false;
//                    express_id = "10";
                    pay_address_take_ll.setVisibility(View.VISIBLE);
                    payAddress.setVisibility(View.GONE);
                    pay_express_general_ll.setVisibility(View.GONE);
                    fright_style_list.setVisibility(View.GONE);
//                    tv_express_title.setVisibility(View.GONE);
                    payPricePay.setText(""+price_pay);
                    mcurrentFright=-1;
                    fright_style_list.updateUI();
                    express_id="";
                }
            }
        });
//        editNum.setText(buy_num + "");
//        editNum.addTextChangedListener(this);
//        buy_num = Integer.parseInt(editNum.getText().toString().trim());
        payBalanceUse.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isUseBalance = isChecked;

            }
        });
        rb_balance_check.setChecked(true);
        activity_balance_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(rb_balance_check.isChecked()){
                    rb_balance_check.setChecked(false);
                }else{
                    rb_balance_check.setChecked(true);
                }
                isUseBalance=rb_balance_check.isChecked();
            }
        });
//
        payBalanceUse.setChecked(true);
        payPricePay.setText("￥"+totalPrice);
        payPriceTotal.setText("￥"+totalPrice);

    }
    private void initRecycle(ArrayList<checkoutcartdata.Data.Cart_goods> data){
//        adapter2= new AdaptList2(mcontext, data, "0");
//
//        adapter2.setLoadMoreView(new CustomLoadMoreView());
//        adapter2.setOnLoadMoreListener(this, mRecyclerView);
////        adapter2.addHeaderView(head);
//        mLayoutManager = new LinearLayoutManager(mcontext);
////        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
//        mRecyclerView.setLayoutManager(mLayoutManager);
//        mRecyclerView.setAdapter(adapter2);
//        ((TextView) view.findViewById(R.id.scroll_total)).setText();
//        mRecyclerView.GetToTop((ImageView) view.findViewById(R.id.top), 1);
    }
    //团长
    private double discount_teamer = 0.0;
    //通用
    private int pos_use_general;
    private String coupon_id_use_general = "0";
    private String coupon_discount_use_general = "0";
    private String coupon_need_amount_use_general = "-1";
    private String coupon_title_use_general = "不使用优惠券";
    //店铺
    private int pos_use_store;
    private String coupon_id_use_store = "0";
    private String coupon_discount_use_store = "0";
    private String coupon_need_amount_use_store = "-1";
    private String coupon_title_use_store = "不使用优惠券";

    @OnClick({ R.id.pay_address_add_ll, R.id.pay_address_ll, R.id.click_resetnetwork_refresh,
            R.id.pay_post, R.id.pay_coupon_store_ll, R.id.pay_coupon_general_ll})
    public void onClick(View view) {
        Intent intent = new Intent(this, TransparentActivity.class);
        switch (view.getId()) {
            case R.id.btn_minus:
//                if (editNum.getText().toString().trim().equals("")) {
//                    editNum.setText("1");
//                } else {
//                    buy_num = Integer.parseInt(editNum.getText().toString().trim());
//                    if (buy_num > 1) {
//                        buy_num--;
//                        editNum.setText(buy_num + "");
//                    }
//                }
//                CalculationPrice();
                break;
            case R.id.btn_plus:
//                if (editNum.getText().toString().trim().equals("")) {
//                    editNum.setText("1");
//                } else if (typeid == 5 || typeid == 6) {
//                    editNum.setText("1");
//                    ObjectUtils.toast(mcontext, "最多只能购买数量1");
//                } else {
//                    buy_num = Integer.parseInt(editNum.getText().toString().trim());
//                    if (buy_num < buy_num_limit) {
//                        buy_num++;
//                        editNum.setText(buy_num + "");
//                    } else {
//                        ObjectUtils.toast(mcontext, "没有更多库存了");
//                    }
//                }
//                CalculationPrice();
                break;
            case R.id.pay_address_add_ll:
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 0);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_NUMBER, 2);
                startActivityForResult(intent, 1);
                break;
            case R.id.pay_address_ll:
                Intent intent_address = new Intent(this, BaseObject.class);
                intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "收货地址");
                startActivityForResult(intent_address, 0);
                break;
            case R.id.click_resetnetwork_refresh:
                break;
            case R.id.pay_post:
//                buy_num = Integer.parseInt(editNum.getText().toString().trim());
                String msg = payMsgEdit.getText().toString().trim();
                if (addressid == null) {
                    ObjectUtils.toast(mcontext, "请选择收货地址");
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 0);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_NUMBER, 2);
                    startActivityForResult(intent, 1);
                    return;
                }
                if (frightexpress_id == null||"".equals(frightexpress_id)) {
                    ObjectUtils.toast(mcontext, "请选择运送方式");
                    return;
                }
                GetToPay(token, buy_num, addressid, express_id, take_address_id, pay_id, coupon_id_use_general, msg, coupon_id_use_store);


                break;
            case R.id.pay_coupon_store_ll:
                final PopPaycoupn pop_store = new PopPaycoupn(mcontext, data, pos_use_store);
                pop_store.show(mcontext.getWindow().getDecorView(), 1);
                pop_store.setPopListDataClickListener(new PopPaycoupn.OnPopListDataClickListener() {
                    @Override
                    public void onData(String id, String discount, String need_amount, String title, int posUse, int type) {
                        if (type == 1) {
                            pos_use_store = posUse;
                            coupon_id_use_store = id;
                            coupon_discount_use_store = discount;
                            coupon_need_amount_use_store = need_amount;
                            coupon_title_use_store = title;
                            if (Double.parseDouble(coupon_need_amount_use_store) > (price_team * buy_num)) {
                                pos_use_store = 0;
                                coupon_id_use_store = "0";
                                coupon_discount_use_store = "0";
                                coupon_need_amount_use_store = "-1";
                                coupon_title_use_store = "不满足优惠";

                            }
                            payCouponStoreTv.setText(coupon_title_use_store);
                        }
                        pop_store.close();
                        CalculationPrice();
                    }
                });
                break;
            case R.id.pay_coupon_general_ll:
                //优惠券通用
                final PopPaycoupn pop_general = new PopPaycoupn(mcontext, data, pos_use_general);
                pop_general.show(mcontext.getWindow().getDecorView(), 0);
                pop_general.setPopListDataClickListener(new PopPaycoupn.OnPopListDataClickListener() {
                    @Override
                    public void onData(String id, String discount, String need_amount, String title, int posUse, int type) {
                        if (type == 0) {
                            pos_use_general = posUse;
                            coupon_id_use_general = id;
                            coupon_discount_use_general = discount;
                            coupon_need_amount_use_general = need_amount;
                            coupon_title_use_general = title;
                            if (Double.parseDouble(coupon_need_amount_use_general) > sub(Double.parseDouble(totalPrice), Double.parseDouble(coupon_discount_use_store))) {
                                pos_use_general = 0;
                                coupon_id_use_general = "0";
                                coupon_discount_use_general = "0";
                                coupon_need_amount_use_general = "-1";
                                coupon_title_use_general = "不满足优惠";
                            }
                            payCouponGeneralTv.setText(coupon_title_use_general);
                        }
                        pop_general.close();
                        CalculationPrice();
                    }
                });
                break;
        }
    }

    private Double price_pay;

    private void CalculationPrice() {
        double price_total = sub(price_team * buy_num, Double.parseDouble(coupon_discount_use_store));
        price_pay = sub(price_team * buy_num, (Double.parseDouble(coupon_discount_use_general)
                + Double.parseDouble(coupon_discount_use_store) + discount_teamer));

//        payPriceTotal.setText("￥" + price_total);
//        if (typeid == 10) {
//            payPricePay.setText("￥" + (deposit * buy_num));
//        } else {
//            payPricePay.setText("￥" + price_pay);
//        }
//        if (price_total < 0) {
//            payPriceTotal.setText("￥0");
//        }
//        if (price_pay < 0) {
//            payPricePay.setText("￥0");
//        }
        MyLog.e("返回通用", coupon_id_use_general + "优惠" + coupon_discount_use_general + "满" + coupon_need_amount_use_general + coupon_title_use_general);
        MyLog.e("返回店铺", coupon_id_use_store + "优惠" + coupon_discount_use_store + "满" + coupon_need_amount_use_store + coupon_title_use_store);
        MyLog.e("数量", buy_num + "支付" + price_pay);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
//        if (editNum.getText().toString().trim().equals("")) {
//            payPriceTotal.setText("￥0");
//            payPricePay.setText("￥0");
//            return;
//        }
//        buy_num = Integer.parseInt(editNum.getText().toString().trim());
//        if (buy_num <= 0) {
//            editNum.setText("1");
//            ObjectUtils.toast(mcontext, "数量必须大于0");
//            return;
//        }
//        if (buy_num > buy_num_limit) {
//            editNum.setText(buy_num_limit + "");
//            ObjectUtils.toast(mcontext, "没有更多库存了");
//            return;
//        }
//        CalculationPrice();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 根据上面发送过去的请求吗来区别
        switch (requestCode) {
            case 0:
            case 1:
//                buy_num = Integer.parseInt(editNum.getText().toString().trim());
//                Getdata(detail_id, buy_num, typeid + "", spec, common_id, option);
                checkout();
                break;
            default:
                break;
        }
    }

    //获取订单数据
    private void Getdata(String id, int num, final String typeid, String spec, String common_id, String option) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERPAY;
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> map = new HashMap<>();
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);
            if(TextUtils.isEmpty(logID)){
                map.put("typeid", typeid);//商品类型
                map.put("num", num + "");
                map.put("id", id);
                map.put("spec", spec);//商品规格
                if (common_id == null) {
                    common_id = "";
                }
                map.put("common_id", common_id);//参团所需要的团ID
                map.put("option", option);//自选
            }else {
                map.put("log_id", logID);
            }
            HttpUtils.post(address, header, map, new paydetailCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                        }

                        @Override
                        public void onResponse(paydetail response, int id) {
                            if (response == null) {
                                ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                                return;
                            }
                            if (response.getCode() == 0) {
                                data = response.getData();
                                if (data != null) {
                                    paydetail.DataBean.MemberBean member = data.getMember();
                                    if (member != null && !TextUtils.isEmpty(member.getUser_money())) {
//                                        payBalanceUse.setText("可用余额（共"+member.getUser_money()+"元）");
                                        tv_balance_name.setText("可用余额（共"+member.getUser_money()+"元）");

                                    }
                                    List<paydetail.DataBean.ExpressBean> express = data.getExpress();
                                    if (data.getTake_address() == null) {
                                        payRadioExpress.setVisibility(View.VISIBLE);
                                        if (ObjectUtils.listHasData(express)) {
                                            express_id = express.get(0).getId();
                                        }
                                    } else if (express == null && data.getTake_address() != null) {
                                        payRadioExpress.setVisibility(View.GONE);
                                        payRadioSelf.setVisibility(View.VISIBLE);
                                        payRadioSelf.setChecked(true);
                                        isCheck = false;
                                        express_id = "10";
                                        pay_address_take_ll.setVisibility(View.VISIBLE);
                                        payAddress.setVisibility(View.GONE);
                                    }
                                    if (data.getAddress() != null) {
                                        payAddressLl.setVisibility(View.VISIBLE);
                                        payAddressAddLl.setVisibility(View.GONE);
                                        payAddressNameaphone.setText(data.getAddress().getName() + "," + data.getAddress().getMobile());
                                        payAddressAddress.setText(data.getAddress().getArea() + data.getAddress().getAddress());
                                        addressid = data.getAddress().getId() + "";
                                    } else {
                                        //手动创建地址
                                        payAddressAddLl.setVisibility(View.VISIBLE);
                                        payAddressLl.setVisibility(View.GONE);
                                    }
                                    //支付方式
                                    mSortListdata.clear();
                                    List<paydetail.DataBean.PaymentBean> payment = data.getPayment();
                                    if (ObjectUtils.listHasData(payment)) {
                                        for (int i = 0; i < payment.size(); i++) {
                                            paydetail.DataBean.PaymentBean paymentBean = payment.get(i);
                                            pay_ids[i] = paymentBean.getPay_id() + "";
                                            if (paymentBean.getPay_code().equals("wxpayapp")) {
                                                mSortListdata.add(new MainTabData("微信", pay_ids[i], R.mipmap.support_pay_wx));
                                            }
                                            if (paymentBean.getPay_code().equals("alipayapp")) {
                                                mSortListdata.add(new MainTabData("支付宝", pay_ids[i], R.mipmap.support_pay_ali));
                                            }
                                        }
                                        pay_id = pay_ids[0];
                                        pay_style = mSortListdata.get(0).getName();
                                        //        mSortListdata.add(new MainTabData("银联(未开通)", "", R.mipmap.support_pay_yl));
                                        payStyleList.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_pay, mSortListdata) {
                                            @Override
                                            public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                                                holder.setText(R.id.pay_name, testBean.getName());
                                                holder.setImageResource(R.id.pay_logo, testBean.getThumb());
                                                if (pospay == position) {//最后选择的位置
                                                    holder.setChecked(R.id.item_list_mine_pay_check, true);
                                                } else {
                                                    holder.setChecked(R.id.item_list_mine_pay_check, false);
                                                }
                                            }
                                        });
                                        payStyleList.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
                                            @Override
                                            public void onItemClick(NestFullListView nestFullListView, View view, int position) {
                                                pospay = position;
                                                nestFullListView.updateUI();
                                                pay_id = mSortListdata.get(position).getId();
                                                pay_style = mSortListdata.get(position).getName();
                                            }
                                        });
                                        payStyleList.updateUI();
                                    }
                                    //商品标题头像等
//                                    payGoodsPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                                    String store_name = data.getStore_name();
                                    if (store_name != null) {
                                        payGoodsStoreName.setText(store_name + "");
                                    } else {
                                        String appName = getResources().getString(R.string.app_name);
                                        payGoodsStoreName.setText( "糖宝果鲜旗舰店");

                                    }
                                    paydetail.DataBean.GoodsBean goods = data.getGoods();
                                    if (goods != null) {
//                                        payGoodsTitle.setText(goods.getName());
//                                        ObjectUtils.photo(mcontext, goods.getImg_cover(), payGoodsThumb);
//                                        payGoodsPrice.setText("￥" + goods.getMarket_price());
//                                        Object goods_spec = goods.getGoods_spec();
//                                        if (goods_spec != null) {
//                                            payGoodsPriceSpec.setText((String) goods_spec);
//                                        }
//                                        //团购价
//                                        price_team = Double.parseDouble(goods.getPrice());
//                                        payGoodsPriceTeam.setText("￥" + price_team);
                                        buy_num_limit = goods.getBuy_num_limit();
                                        price_pay = Double.parseDouble(goods.getSubtotal());
                                        //团长优惠
                                        String discount_amount = goods.getDiscount_amount();
                                        if (discount_amount == null || discount_amount.equals("0.00") || discount_amount.equals("0")) {
                                            discount_teamer = 0.0;
                                            payCouponTeamerLl.setVisibility(View.GONE);
                                        } else {
                                            payCouponTeamerLl.setVisibility(View.VISIBLE);
                                            discount_teamer = Double.parseDouble(discount_amount);
                                        }
                                        payCouponTeamerTv.setText("-￥" + discount_teamer);
                                    }
//                                    payPriceTotal.setText("￥" + price_pay);
                                    deposit = Double.parseDouble(goods.getDeposit());
                                }
                                if (typeid.equals("10")) {
                                    payPriceDepositLl.setVisibility(View.VISIBLE);
                                    payPriceDeposit.setText("￥" + deposit);
                                    payCouponGeneralLl.setVisibility(View.GONE);
                                    payCouponStoreLl.setVisibility(View.GONE);
                                    payCouponTeamerLl.setVisibility(View.GONE);
//                                    payPricePay.setText("￥" + deposit);
                                    payTip.setText("支付定金后请在72小时内分享到微信朋友圈邀请好友一起拼团呦，阶梯团根据拼团人数价格会不断变动，"
                                            + "因此采取在预定款上加补差额的方式，如果有客户不补齐尾款的话，阶梯团也不会把定金退给客户。");
                                } else {
//                                    payPricePay.setText("￥" + price_pay);
                                    payTip.setText("付款完成后请分享到微信朋友圈邀请好友一起拼团吧~，超过72小时后人数不足系统自动退款");
                                    if (typeid.equals("0")) {
                                        payTip.setVisibility(View.GONE);
                                    }
                                }
                                token = data.getToken();

                                List<paydetail.DataBean.TakeAddressBean> take_address = data.getTake_address();
                                if (ObjectUtils.listHasData(take_address)) {
                                    take_address_id = data.getTake_address().get(0).getId();
                                    payRadioSelf.setVisibility(View.VISIBLE);
                                    payAddressSelfLl.setVisibility(View.VISIBLE);
                                    pay_address_self_empty_tv.setVisibility(View.GONE);
                                    initExpressself(take_address);
                                } else {
                                    payAddressSelfLl.setVisibility(View.GONE);
                                    pay_address_self_empty_tv.setVisibility(View.VISIBLE);
                                }
                                ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                            } else {
                                noData.setVisibility(View.VISIBLE);
                                noDataTv.setText(response.getMsg());
                                noDataTv.setVisibility(View.VISIBLE);
                            }
                        }
                    }
            );
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }

    private void initExpressself(final List<paydetail.DataBean.TakeAddressBean> take_address) {

        payAddressSelfLl.setAdapter(new NestFullListViewAdapter<paydetail.DataBean.TakeAddressBean>(R.layout.item_pay_address, take_address) {
            @Override
            public void onBind(int position, paydetail.DataBean.TakeAddressBean testBean, NestFullViewHolder holder) {
                holder.setText(R.id.item_pay_address_detail, testBean.getArea() + testBean.getAddress());
                holder.setText(R.id.item_pay_address_phone, "电话：" + testBean.getMobile());

                if (posexpress == position) {//最后选择的位置
                    holder.setChecked(R.id.item_pay_address_check, true);
                } else {
                    holder.setChecked(R.id.item_pay_address_check, false);
                }
            }
        });

        payAddressSelfLl.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, int position) {
                posexpress = position;
                nestFullListView.updateUI();
                take_address_id = take_address.get(position).getId();
            }
        });
    }

    //生成订单以及付款
String frightexpress_id="";

    private void GetToPay(String token, int num, String address_id, String express_id, String take_address_id, final String pay_id, String coupon_id, String order_tip, String coupon_id_store) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            String address = ConstantsUrl.domain +"order/cart_done";
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);
            HashMap<String, String> map = new HashMap<>();
//            map.put("token", token);
//            map.put("num", num + "");
//            map.put("address_id", address_id);//地址id
//            map.put("express_id", express_id);//地址id
//            map.put("take_address_id", take_address_id);//地址id
//            MyLog.e("shishizhelidepay_id", pay_id);
//            map.put("pay_id", pay_id);//支付方式id
//            map.put("coupon_id", coupon_id);//优惠券id
//            map.put("coupon_id_sid", coupon_id_store);//店铺优惠券id
            map.put("order_tip", order_tip);//买家留言
            MyLog.e("inest","pay_id="+pay_id);
            if(isUseBalance){
                map.put("balance_pay", "1");//使用余额
            }
            map.put("address_id",addressid);
            map.put("express_id",frightexpress_id);
            map.put("order_sn","");

            if (pay_style.equals("支付宝")) {
                map.put("pay_id", pay_id);//支付
                HttpUtils.post(address, header, map, new paydoneCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressLoading.setVisibility(View.GONE);
                    }

                    @Override
                    public void onResponse(paydone response, int id) {
                        if (response == null) {
                            progressLoading.setVisibility(View.GONE);
                            return;
                        }
                        paydone.DataBean data = response.getData();
                        if (response.isFlag() && data != null) {
                            order_sn = data.getOrder_sn();
                            sharedPreferences = getSharedPreferences("wechat_temporary", 0); //私有数据
                            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                            editor.putString(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ORDER_SN, order_sn);
                            editor.commit();//
                            isReallyOrder_flag = response.isFlag();

                            if (isReallyOrder_flag) {
                                if (data.getPayment() != null) {
                                    orderInfo = data.getPayment();
                                    //支付宝支付发起
                                    Runnable payRunnable = new Runnable() {
                                        @Override
                                        public void run() {
                                            PayTask alipay = new PayTask(mcontext);
                                            Map<String, String> result = alipay.payV2(orderInfo, true);
                                            Message msg = new Message();
                                            msg.what = SDK_PAY_FLAG;
                                            msg.obj = result;
                                            mHandler.sendMessage(msg);
                                        }
                                    };
                                    Thread payThread = new Thread(payRunnable);
                                    payThread.start();
                                } else {
                                    String common_id = data.getCommon_id();
                                    if(typeid == 0 || TextUtils.isEmpty(common_id)){
                                        ToOrder(0, 4);
                                    }else {
                                        toTeamDetail(common_id);
                                    }
                                }
                                progressLoading.setVisibility(View.GONE);
                            }
                        } else {
                            Toast.makeText(mcontext, response.getMsg(), Toast.LENGTH_LONG).show();
                            progressLoading.setVisibility(View.GONE);
                            return;
                        }
                    }
                });
            } else {
                map.put("pay_id", "61");//支付
                HttpUtils.post(address, header, map, new wchatpaydoneCallback2() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressLoading.setVisibility(View.GONE);
                        MyLog.e("inest","wchatpaydoneCallback="+e.getMessage());
                        finish();
                    }

                    @Override
                    public void onResponse(wchatpaydone2 response, int id) {
                        if (response == null) {
                            progressLoading.setVisibility(View.GONE);
                            return;
                        }
//                        wchatpaydone2.DataBean data = response.getData();
                        MyLog.e("inest","wchatpaydoneCallback="+response);

                        topay(response.getOrder_sn());

//                        if (response.isFlag() && data != null) {
//                            order_sn = data.getOrder_sn();
//                            sharedPreferences = getSharedPreferences("wechat_temporary", 0); //私有数据
//                            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
//                            editor.putString(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ORDER_SN, order_sn);
//                            editor.commit();//
//                            isReallyOrder_flag = response.isFlag();
//                            if (isReallyOrder_flag) {
//                                wchatpaydone.PaymentBean payment = data.getPayment();
//                                if (payment != null) {
//                                    //微信支付发起
//                                    iwxapi = WXAPIFactory.createWXAPI(mcontext, ConstantsUrl.WX_APPID, true);
//                                    iwxapi.registerApp(ConstantsUrl.WX_APPID);
//                                    PayReq req = new PayReq();
//                                    req.appId = ConstantsUrl.WX_APPID;
//                                    req.partnerId = payment.getPartnerid();
//                                    req.prepayId = payment.getPrepayid();
//                                    req.packageValue = payment.getWxpackage();
//                                    req.nonceStr = payment.getNoncestr();
//                                    req.timeStamp = payment.getTimestamp();
//                                    req.sign = payment.getSign();
//                                    iwxapi.sendReq(req);
//                                }
//                            } else {
//                                String common_id = data.getCommon_id();
//                                if(typeid == 0 || TextUtils.isEmpty(common_id)){
//                                    ToOrder(0, 4);
//                                }else {
//                                    toTeamDetail(common_id);
//                                }
//                            }
////                            Timer timer = new Timer();// 实例化Timer类
////                            timer.schedule(new TimerTask() {
////                                public void run() {
////                                    finish();
////                                }
////                            }, 3000);// 这里百毫秒
//                            progressLoading.setVisibility(View.GONE);
//                        } else {
////                            ObjectUtils.toast(mcontext, response.getMsg());
//                            progressLoading.setVisibility(View.GONE);
//                            Toast.makeText(mcontext, response.getMsg(), Toast.LENGTH_LONG).show();
//                            return;
//                        }
                    }


                });
            }
        } else {
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }
    private void topay(String order_sn) {
        String address = ConstantsUrl.domain +"order/pay";
        String getid = LoginState.getInstance().getid(mcontext);
        String getpd = LoginState.getInstance().getpd(mcontext);
        HashMap<String, String> header = new HashMap<>();
        header.put("UID", getid);
        header.put("UPSW", getpd);
        HashMap<String, String> map = new HashMap<>();
            map.put("order_sn", order_sn);
//            map.put("out_trade_no", out_trade_no);


        HttpUtils.get(address, header, map, new cartPayCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
MyLog.e("inest","topay=error+"+e.getMessage());
            }

            @Override
            public void onResponse(cartPayData response, int id) {
                MyLog.e("inest","topay=onResponse");
                cartPayData.data data=response.getData();
                        if (response.isFlag() && data != null) {
                           String order_sn = data.getOrder_sn();
                            sharedPreferences = getSharedPreferences("wechat_temporary", 0); //私有数据
                            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                            editor.putString(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ORDER_SN, order_sn);
                            editor.commit();//
                            isReallyOrder_flag = response.isFlag();
                            if (isReallyOrder_flag) {
                                cartPayData.paymentData payment = data.getPayment();
                                if (payment != null) {
                                    //微信支付发起
                                    iwxapi = WXAPIFactory.createWXAPI(mcontext, ConstantsUrl.WX_APPID, true);
                                    iwxapi.registerApp(ConstantsUrl.WX_APPID);
                                    PayReq req = new PayReq();
                                    req.appId = ConstantsUrl.WX_APPID;
                                    req.partnerId = payment.getPartnerid();
                                    req.prepayId = payment.getPrepayid();
                                    req.packageValue = payment.getWxpackage();
                                    req.nonceStr = payment.getNoncestr();
                                    req.timeStamp = ""+payment.getTimestamp();
                                    req.sign = payment.getSign();
                                    iwxapi.sendReq(req);
                                }
                            } else {
//                                String common_id = data.getCommon_id();
                                if(typeid == 0 || TextUtils.isEmpty(common_id)){
                                    ToOrder(0, 4);
                                }else {
                                    toTeamDetail(common_id);
                                }
                            }
//                            Timer timer = new Timer();// 实例化Timer类
//                            timer.schedule(new TimerTask() {
//                                public void run() {
//                                    finish();
//                                }
//                            }, 3000);// 这里百毫秒
                            progressLoading.setVisibility(View.GONE);
                        } else {
//                            ObjectUtils.toast(mcontext, response.getMsg());
                            progressLoading.setVisibility(View.GONE);
                            Toast.makeText(mcontext, response.getMsg(), Toast.LENGTH_LONG).show();
                            return;
                        }
//                toPaySucess();
            }
        });
    }

    private  void toPaySucess(){
       String url="http://www.tbfresh.cn/flow/pay_succ";
       Intent intent=new Intent(mcontext,BaseWeb.class);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_WEB_URL,url);
        startActivity(intent);
    }
    private void ToOrder(int tab, int type) {
        if (LoginState.getInstance().isLogin(mcontext)) {
            Intent intent = new Intent(mcontext, MainTab.class);
            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, tab);
            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, type);
            startActivity(intent);
            setResult(1);
            finish();
        } else {
            startActivity(new Intent(mcontext, LoginActivity.class));
        }
    }

    private void toTeamDetail(String common_id) {
        Intent intent_tuan = new Intent(mcontext, BaseObject.class);
        intent_tuan.putExtra("title", "团详情");
        intent_tuan.putExtra("need_id", common_id);
        mcontext.startActivity(intent_tuan);
        setResult(1);
        finish();
    }

    //支付成功去分享页面
    private void GetToSharePage() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERPAYDONETOShare;
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);
            HashMap<String, String> map = new HashMap<>();
            map.put("order_sn", order_sn);
            MyLog.e("order_snzhifubao", order_sn.toString());
            HttpUtils.get(address, header, map, new paydonetoshareCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    progressLoading.setVisibility(View.GONE);
                    finish();
                }

                @Override
                public void onResponse(paydonetoshare response, int id) {
                    if (response == null) {
                        progressLoading.setVisibility(View.GONE);
                        finish();
                        return;
                    }
                    paydonetoshare.DataBean data = response.getData();
                    if (data != null) {
                        common_id = data.getCommon_id();
                        if (Integer.parseInt(common_id) > 0) {
                            toTeamDetail(common_id);
                        } else {
                            ToOrder(0, 4);
                        }
                    }
                }
            });
        } else {
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }

    public double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }

    ArrayList<checkoutcartdata.Data.Cart_goods> listdata=new ArrayList<>();
    int mcurrentFright=-1;
    private void checkout(){
        String address = ConstantsUrl.domain + "order/checkout";
        HashMap<String, String> map = new HashMap<>();
        map.put("order_sn", "");
        map.put("address_id", "");
        HttpUtils.get(address, map, new checkoutcartCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyLog.e("inest","listdata=onError"+e.getMessage());
            }

            @Override
            public void onResponse(checkoutcartdata response, int id) {
                MyLog.e("inest","listdata=onResponse");
        if(response.getFlag()){

           checkoutcartdata.Data checkoutcartdata= response.getData();
                listdata.clear();
                if(listdata.size()>0){
                    listdata=null;
                    listdata=new ArrayList();
                }
                for (int i=0;i<response.getData().getCart_goods().size();i++){
                    if(cartidlist.contains(response.getData().getCart_goods().get(i).getId())){
                        listdata.add(response.getData().getCart_goods().get(i));
                    }
                }
//                Getdata(listdata.get(0).getGoods_id(), 1, listdata.get(0).getType(), listdata.get(0).getGoods_spec(), "", "");
//            payBalanceUse.setText("可用余额（共"+response.getData().getFlow_user_money()+"元）");
            tv_balance_name.setText("可用余额（共"+response.getData().getFlow_user_money()+"元）");
//            String store_name = data.getStore_name();
//            if (store_name != null) {
//                payGoodsStoreName.setText(store_name + "");
//            } else {
                String appName = getResources().getString(R.string.app_name);
                payGoodsStoreName.setText(appName + "商城自营");
            if (checkoutcartdata.getAddress() != null&&checkoutcartdata.getAddress().size()>0) {
                payAddressLl.setVisibility(View.VISIBLE);
                payAddressAddLl.setVisibility(View.GONE);
                payAddressNameaphone.setText(checkoutcartdata.getAddress().get(0).getName() + "," + checkoutcartdata.getAddress().get(0).getMobile());
                payAddressAddress.setText(checkoutcartdata.getAddress().get(0).getArea() + checkoutcartdata.getAddress().get(0).getAddress());
                addressid = checkoutcartdata.getAddress().get(0).getId() + "";
            } else {
                //手动创建地址
                payAddressAddLl.setVisibility(View.VISIBLE);
                payAddressLl.setVisibility(View.GONE);
            }
            ArrayList<checkoutcartdata.Data.FrightData> FrightList=new ArrayList<>();
            FrightList=checkoutcartdata.getFright();
            final ArrayList<checkoutcartdata.Data.FrightData> finalFrightList = FrightList;
            final frightAdapter myfrightAdapter=new frightAdapter(R.layout.item_accounts_online, finalFrightList);
            fright_style_list.setAdapter(myfrightAdapter);
            //            fright_style_list.setAdapter(new NestFullListViewAdapter(R.layout.item_accounts_online, finalFrightList) {
//                @Override
//                public void onBind(int i, Object o, NestFullViewHolder nestFullViewHolder) {
//                    mcurrentFright=i;
//                    fright_style_list.setAdapter(new NestFullListViewAdapter(R.layout.item_accounts_online, finalFrightList) {
//                        @Override
//                        public void onBind(final int i, Object o, NestFullViewHolder nestFullViewHolder) {
//                            if(i==mcurrentFright){
//                                nestFullViewHolder.setChecked(R.id.item_account_online_check,true);
//                            }else{
//                                nestFullViewHolder.setChecked(R.id.item_account_online_check,false);
//
//                            }
//                            nestFullViewHolder.setText(R.id.tv_account_online_refill, finalFrightList.get(i).getName());
//                            nestFullViewHolder.getView(R.id.tv_account_online_send).setVisibility(View.GONE);
//                            ((TextView)nestFullViewHolder.getView(R.id.tv_account_online_refill)).setTextSize(16);
////                            frightexpress_id=finalFrightList.get(i).getId();
//                            nestFullViewHolder.getView(R.id.item_account_online_check).setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//                                    mcurrentFright=i;
//                                    fright_style_list.setAdapter(new NestFullListViewAdapter(R.layout.item_accounts_online, finalFrightList) {
//                                        @Override
//                                        public void onBind(int i, Object o, NestFullViewHolder nestFullViewHolder) {
//                                            if(i==mcurrentFright){
//                                                nestFullViewHolder.setChecked(R.id.item_account_online_check,true);
//                                            }else{
//                                                nestFullViewHolder.setChecked(R.id.item_account_online_check,false);
//
//                                            }
//                                            nestFullViewHolder.setText(R.id.tv_account_online_refill, finalFrightList.get(i).getName());
//                                            nestFullViewHolder.getView(R.id.tv_account_online_send).setVisibility(View.GONE);
//                                            ((TextView)nestFullViewHolder.getView(R.id.tv_account_online_refill)).setTextSize(16);
////                                            frightexpress_id=finalFrightList.get(i).getId();
////                                            getFee_shopping(totalPrice);
//                                        }
//                                    });
//                                }
//                            });
//                        }
//
//
//                    });

//                }
//            });
            fright_style_list.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
                @Override
                public void onItemClick(NestFullListView nestFullListView, View view, final int i) {
                    mcurrentFright=i;
//                    RadioButton mRadioButton=(RadioButton) nestFullListView.getChildAt(i).findViewById(R.id.item_account_online_check);
//                    mRadioButton.setChecked(true);
                    fright_style_list.setAdapter(myfrightAdapter);
//                    fright_style_list.setAdapter(new NestFullListViewAdapter(R.layout.item_accounts_online, finalFrightList) {
//                        @Override
//                        public void onBind(int i, Object o, NestFullViewHolder nestFullViewHolder) {
//                          if(i==mcurrentFright){
//                              nestFullViewHolder.setChecked(R.id.item_account_online_check,true);
//                          }else{
//                              nestFullViewHolder.setChecked(R.id.item_account_online_check,false);
//
//                          }
//                            nestFullViewHolder.setText(R.id.tv_account_online_refill, finalFrightList.get(i).getName());
//                            nestFullViewHolder.getView(R.id.tv_account_online_send).setVisibility(View.GONE);
//                            ((TextView)nestFullViewHolder.getView(R.id.tv_account_online_refill)).setTextSize(16);
//
//
//
//                        }
//                    });
                    Handler handler=new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            if(finalFrightList!=null) {
                                frightexpress_id = finalFrightList.get(i).getId();
//                    MyLog.e("inest","finalFrightList="+frightexpress_id+"   "+finalFrightList.get(i).getName());
                                ajaxCalculateShippingCosts(frightexpress_id, addressid);
                            }

                        }
                    },500);


                }
            });
            getFee_shopping(totalPrice);
            //支付方式
            mSortListdata.clear();
            ArrayList<checkoutcartdata.Data.Payment>  payment = checkoutcartdata.getPayment();
            if (ObjectUtils.listHasData(payment)) {
                for (int i = 0; i < payment.size(); i++) {
                    checkoutcartdata.Data.Payment paymentBean = payment.get(i);
                    pay_ids[i] = paymentBean.getPay_id() + "";
                    if (paymentBean.getPay_code().equals("wxpay")) {
                        mSortListdata.add(new MainTabData("微信", pay_ids[i], R.mipmap.support_pay_wx));
                    }
                    if (paymentBean.getPay_code().equals("alipay")) {
                        mSortListdata.add(new MainTabData("支付宝", pay_ids[i], R.mipmap.support_pay_ali));
                    }
                }
                pay_id = pay_ids[0];
                pay_style = mSortListdata.get(0).getName();
                //        mSortListdata.add(new MainTabData("银联(未开通)", "", R.mipmap.support_pay_yl));
                payStyleList.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_pay, mSortListdata) {
                    @Override
                    public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                        holder.setText(R.id.pay_name, testBean.getName());
                        holder.setImageResource(R.id.pay_logo, testBean.getThumb());
                        if (pospay == position) {//最后选择的位置
                            holder.setChecked(R.id.item_list_mine_pay_check, true);
                        } else {
                            holder.setChecked(R.id.item_list_mine_pay_check, false);
                        }
                    }
                });
                payStyleList.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
                    @Override
                    public void onItemClick(NestFullListView nestFullListView, View view, int position) {
                        pospay = position;
                        nestFullListView.updateUI();
                        pay_id = mSortListdata.get(position).getId();
                        pay_style = mSortListdata.get(position).getName();
                    }
                });
                payStyleList.updateUI();
            }

//            }
//                initRecycle(listdata);
                mRecyclerView.setAdapter(new BaseAdapter() {
                    LayoutInflater mInflater= LayoutInflater.from(mcontext);
                    @Override
                    public int getCount() {
                        return listdata.size();
                    }

                    @Override
                    public Object getItem(int position) {
                        return null;
                    }

                    @Override
                    public long getItemId(int position) {
                        return 0;
                    }

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        ViewHolder holder;
                        //观察convertView随ListView滚动情况

                        if (convertView == null) {
                            convertView = mInflater.inflate(R.layout.item_pay_goods,null);
                            holder = new ViewHolder();
                            /**得到各个控件的对象*/
                            holder.pay_goods_title=(TextView) convertView.findViewById(R.id.pay_goods_title);
                            holder.pay_goods_price_team=(TextView) convertView.findViewById(R.id.pay_goods_price_team);
                            holder.pay_goods_price_spec=(TextView) convertView.findViewById(R.id.pay_goods_price_spec);
                            holder.pay_goods_num=(TextView) convertView.findViewById(R.id.pay_goods_num);
                            holder.pay_goods_thumb=(ImageView) convertView.findViewById(R.id.pay_goods_thumb);

                            convertView.setTag(holder);//绑定ViewHolder对象
                        }
                        else{
                            holder = (ViewHolder)convertView.getTag();//取出ViewHolder对象
                        }
                        holder.pay_goods_title.setText(listdata.get(position).getGoods_name());
                        holder.pay_goods_price_team.setText(listdata.get(position).getGoods_price());
                        holder.pay_goods_price_spec.setText(listdata.get(position).getGoods_spec());
                        holder.pay_goods_num.setText("×"+listdata.get(position).getQty());
                       ObjectUtils.photo2(mcontext,listdata.get(position).getImg_src(),holder.pay_goods_thumb);
                        return convertView;
                    }
                    /**存放控件*/
                     final class ViewHolder{
                        public TextView pay_goods_title;
                        public TextView pay_goods_price_team;
                        public TextView pay_goods_price_spec;
                        public TextView pay_goods_num;
                        public ImageView pay_goods_thumb;
//                        public Button   bt;
                    }
                });
        }
//
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {

    }
public class frightAdapter extends NestFullListViewAdapter {
     ArrayList<checkoutcartdata.Data.FrightData> finalFrightList ;
    //
    public frightAdapter(int mItemLayoutId, ArrayList<checkoutcartdata.Data.FrightData> mDatas) {
        super(mItemLayoutId, mDatas);

         finalFrightList = mDatas;
    }

    @Override
    public void onBind(final int i, Object o, NestFullViewHolder nestFullViewHolder) {
        if(i==mcurrentFright){
            nestFullViewHolder.setChecked(R.id.item_account_online_check,true);
        }else{
            nestFullViewHolder.setChecked(R.id.item_account_online_check,false);

        }
        nestFullViewHolder.setText(R.id.tv_account_online_refill, finalFrightList.get(i).getName());
        nestFullViewHolder.getView(R.id.tv_account_online_send).setVisibility(View.GONE);
        ((TextView)nestFullViewHolder.getView(R.id.tv_account_online_refill)).setTextSize(16);
//                            frightexpress_id=finalFrightList.get(i).getId();

    }
}


    public class AdaptList2 extends BaseMultiItemQuickAdapter<checkoutcartdata.Data.Cart_goods,BaseViewHolder> {
        public AdaptList2(Context context, ArrayList<checkoutcartdata.Data.Cart_goods> data, String type) {
            super(data);
            addItemType(ConstantsUrl.BRANDDISCOUNTMAINITEMTYPE, R.layout.item_pay_goods);
        }

        @Override
        protected void convert(BaseViewHolder helper, checkoutcartdata.Data.Cart_goods item) {
            helper.setText(R.id.pay_goods_title,item.getGoods_name());
//            helper.setText(R.id.tv_item_group_secondtitle,item.getDesc());
//            Gson gson=new Gson();
//            thumbsData mthumbsData=  gson.fromJson(item.getThumbs().replace("[","").replace("]",""), thumbsData.class);
//            ObjectUtils.photo(mcontext, "http://www.tbfresh.cn"+mthumbsData.getPath(),(ImageView) helper.getView(R.id.iv_item_group) );



//            NestFullListView  ss= (NestFullListView) helper.getView(R.id.item_group_maingrid);
//            final ArrayList<GroupMainData.DataBean.topiclistdetail.goodsdetail> goodsdetailList=new ArrayList();
//            if(item.getList()!=null&&item.getList().size()>0){
//
//
//                goodsdetailList.addAll(item.getList());
//                goodsdetailList.add(new GroupMainData.DataBean.topiclistdetail.goodsdetail());
//
//            }

//            if(item.getList()==null||item.getList().size()==0) {
//                ss.setVisibility(View.GONE);
//            }



//            ss.setAdapter(new NestFullListViewAdapter<GroupMainData.DataBean.topiclistdetail.goodsdetail>(R.layout.item_group_fragment_main, goodsdetailList) {
//
//
//                @Override
//                public void onBind(final int position, GroupMainData.DataBean.topiclistdetail.goodsdetail testBean, NestFullViewHolder holder) {
//
//                    if(position==goodsdetailList.size()-1){
//
//                    }
//
//                    holder.setText(R.id.item_grid_fragment_sort_tv, testBean.getName());
//                    ObjectUtils.photo(mcontext, testBean.getImg_cover(), ((ImageView) holder.getView(R.id.item_grid_fragment_sort_img)));
//                    String price1 = testBean.getPrice();
//                    SpannableString msp = new SpannableString("￥" + price1);
//                    msp.setSpan(new AbsoluteSizeSpan(10, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//
//                    ((TextView) holder.getView(R.id.tv_item_grid_fragment_price)).setText(msp);
//                    holder.getView(R.id.iv_item_grid_fragment_add).setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
////                            addToCart(goodsdetailList.get(position).getId());
//
//                        }
//                    });
//                }
//
//
//            });
//
//            ss.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
//                @Override
//                public void onItemClick(NestFullListView nestFullListView, View view, int i) {
//                    ObjectUtils.ToDetailActivity(mcontext, 1, goodsdetailList.get(i).getId(), "");
//                }
//            });


        }
    }


boolean  isFee=true;
    public void getFee_shopping(String price){
        String address = ConstantsUrl.domain + "order/fee_shopping";
        HashMap<String, String> map = new HashMap<>();
        map.put("price", price);

        HttpUtils.get(address, null, map, new feeShoppingCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(feeShoppingdata response, int id) {
                if("0".equals(""+response.getData().getIs_fee())){
                    isFee=true;
                }else{
                    isFee=false;
                }
            }
        });
    }

    private void ajaxCalculateShippingCosts(String express_id,String addressid) {

        String address = ConstantsUrl.domain + "order/ajaxCalculateShippingCosts_Cart";
        HashMap<String, String> map = new HashMap<>();
        map.put("express_id", express_id);
        map.put("address_id", addressid);
//        MyLog.e("inest","express_id="+express_id+"    "+addressid);

        HttpUtils.get(address, map, new ajaxCalculateShippingCostsCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                MyLog.e("inest","ajaxCalculateShippingCostsCallback="+e.getMessage());
            }

            @Override
            public void onResponse(CalculateShippingCostsData response, int id) {
                if(response!=null&&response.getData()!=null){

                    String express_price = ""+response.getData().getPrice();
//                    MyLog.e("inest","express_price="+express_price+"     "+totalPrice );
                    double v = Double.parseDouble(express_price);
                    double v2 = Double.parseDouble(totalPrice);
                    if(isFee){

                        payPricePay.setText(""+v2);
                    }else{
                        double v1 = v2 + v;
                        payPricePay.setText(""+v1);
                    }


                    pay_express_general_ll.setVisibility(View.VISIBLE);
                    pay_express_name_tv.setText(response.getData().getExpress());
                    if(isFee){
                        pay_express_price_tv.setText("0");
                    }else{
                        pay_express_price_tv.setText(express_price);
                    }

                }else{
                    if(response.getCode()==400001){
                        Toast.makeText(mcontext,"订单已提交",Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });
    }




    private void GetToPay2(String token, int num, String address_id, String express_id, String take_address_id, final String pay_id, String coupon_id, String order_tip, String coupon_id_store) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERPAYDONE;
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);
            HashMap<String, String> map = new HashMap<>();
            map.put("token", token);
            map.put("num", num + "");
            map.put("address_id", address_id);//地址id
            map.put("express_id", express_id);//地址id
            map.put("take_address_id", take_address_id);//地址id
            MyLog.e("shishizhelidepay_id", pay_id);
            map.put("pay_id", pay_id);//支付方式id
            map.put("coupon_id", coupon_id);//优惠券id
            map.put("coupon_id_sid", coupon_id_store);//店铺优惠券id
            map.put("order_tip", order_tip);//买家留言
            if(isUseBalance){
                map.put("balance_pay", "1");//使用余额
            }

            if (pay_style.equals("支付宝")) {
                HttpUtils.post(address, header, map, new paydoneCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressLoading.setVisibility(View.GONE);
                    }

                    @Override
                    public void onResponse(paydone response, int id) {
                        if (response == null) {
                            progressLoading.setVisibility(View.GONE);
                            return;
                        }
                        paydone.DataBean data = response.getData();
                        if (response.isFlag() && data != null) {
                            order_sn = data.getOrder_sn();
                            sharedPreferences = getSharedPreferences("wechat_temporary", 0); //私有数据
                            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                            editor.putString(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ORDER_SN, order_sn);
                            editor.commit();//
                            isReallyOrder_flag = response.isFlag();

                            if (isReallyOrder_flag) {
                                if (data.getPayment() != null) {
                                    orderInfo = data.getPayment();
                                    //支付宝支付发起
                                    Runnable payRunnable = new Runnable() {
                                        @Override
                                        public void run() {
                                            PayTask alipay = new PayTask(mcontext);
                                            Map<String, String> result = alipay.payV2(orderInfo, true);
                                            Message msg = new Message();
                                            msg.what = SDK_PAY_FLAG;
                                            msg.obj = result;
                                            mHandler.sendMessage(msg);
                                        }
                                    };
                                    Thread payThread = new Thread(payRunnable);
                                    payThread.start();
                                } else {
                                    String common_id = data.getCommon_id();
                                    if(typeid == 0 || TextUtils.isEmpty(common_id)){
                                        ToOrder(0, 4);
                                    }else {
                                        toTeamDetail(common_id);
                                    }
                                }
                                progressLoading.setVisibility(View.GONE);
                            }
                        } else {
                            Toast.makeText(mcontext, response.getMsg(), Toast.LENGTH_LONG).show();
                            progressLoading.setVisibility(View.GONE);
                            return;
                        }
                    }
                });
            } else {
                HttpUtils.post(address, header, map, new wchatpaydoneCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressLoading.setVisibility(View.GONE);
                        finish();
                    }

                    @Override
                    public void onResponse(wchatpaydone response, int id) {
                        if (response == null) {
                            progressLoading.setVisibility(View.GONE);
                            return;
                        }
                        wchatpaydone.DataBean data = response.getData();
                        if (response.isFlag() && data != null) {
                            order_sn = data.getOrder_sn();
                            sharedPreferences = getSharedPreferences("wechat_temporary", 0); //私有数据
                            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                            editor.putString(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ORDER_SN, order_sn);
                            editor.commit();//
                            isReallyOrder_flag = response.isFlag();
                            if (isReallyOrder_flag) {
                                wchatpaydone.PaymentBean payment = data.getPayment();
                                if (payment != null) {
                                    //微信支付发起
                                    iwxapi = WXAPIFactory.createWXAPI(mcontext, ConstantsUrl.WX_APPID, true);
                                    iwxapi.registerApp(ConstantsUrl.WX_APPID);
                                    PayReq req = new PayReq();
                                    req.appId = ConstantsUrl.WX_APPID;
                                    req.partnerId = payment.getPartnerid();
                                    req.prepayId = payment.getPrepayid();
                                    req.packageValue = payment.getWxpackage();
                                    req.nonceStr = payment.getNoncestr();
                                    req.timeStamp = payment.getTimestamp();
                                    req.sign = payment.getSign();
                                    iwxapi.sendReq(req);
                                }
                            } else {
                                String common_id = data.getCommon_id();
                                if(typeid == 0 || TextUtils.isEmpty(common_id)){
                                    ToOrder(0, 4);
                                }else {
                                    toTeamDetail(common_id);
                                }
                            }
//                            Timer timer = new Timer();// 实例化Timer类
//                            timer.schedule(new TimerTask() {
//                                public void run() {
//                                    finish();
//                                }
//                            }, 3000);// 这里百毫秒
                            progressLoading.setVisibility(View.GONE);
                        } else {
//                            ObjectUtils.toast(mcontext, response.getMsg());
                            progressLoading.setVisibility(View.GONE);
                            Toast.makeText(mcontext, response.getMsg(), Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                });
            }
        } else {
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }

}